package com.qf.controller;

import com.qf.dto.R;
import com.qf.entity.SysUserInfo;
import com.qf.events.UserLoginEvent;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

/**
 * @Author ztf
 * @Date 20:55 2021/12/27
 **/
@RestController
@RequestMapping("user")
public class UserController {
    private UserService userService;
    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 注册接口
     *
     * @param userInfo 用户信息
     * @return 成功
     */
    @PostMapping("/register")
    public R register(@RequestBody SysUserInfo userInfo) {
        userService.addUser(userInfo);
        return R.setOK();
    }

    /**
     * @param username 用户名
     * @param password 密码
     * @param session  session
     * @return 成功
     */
    @PostMapping("/login")
    public R login(String username, String password, HttpSession session) {
        SysUserInfo userInfo = userService.login(username, password);
        session.setAttribute("user", userInfo);

        //更新用户登录信息事件
        context.publishEvent(new UserLoginEvent());

        return R.setOK(userInfo.getUsername() + "登录成功");
    }

}
